package com.touchalachs.core.ui;

import java.util.ArrayList;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;

public class TextArea extends BasicUIElement {

	private boolean drawBackground = false;
	private volatile int fontSize = 32;
	private float lineHeight = 1.3f;
	
	public String[] lines;
	
	/**
	 * relative size 0..100
	 */
	public TextArea(int x, int y, int w, int h, String text, Point screenSize) {
		super(x, y, w, h, screenSize);
		setText(text);
	}
	
	public void setText(String text){
		calcLines(text);
	}

	private void calcLines(String text) {
		int screenWidth = getDimension().width();
		Paint p = new Paint();
		p.setTextSize(fontSize);
		ArrayList<String> tempLines= new ArrayList<String>();
		String[] paragraphs = text.split("\n");
		for (int pi=0; pi<paragraphs.length; pi++){
			String[] words = paragraphs[pi].split(" ");
			p.measureText(text);
			String currentLine = "";
			for(int i=0; i<words.length; i++){
				if (p.measureText(words[i]) > screenWidth){
					if (!currentLine.isEmpty()){
						tempLines.add(currentLine);
						currentLine = "";
					}
					tempLines.add(words[i]);
				}else{
					String appendedToLine;
					if (currentLine.isEmpty()){
						appendedToLine = words[i];
					}else{
						appendedToLine = currentLine+ " " + words[i];
					}
					if (p.measureText(appendedToLine) > screenWidth){
						tempLines.add(currentLine);
						currentLine = words[i];
					}else{
						currentLine = appendedToLine;
					}
				}
			}
			if (!currentLine.isEmpty()){
				tempLines.add(currentLine);
			}
		}
		lines = new String[tempLines.size()];
		for(int i=0; i<tempLines.size(); i++){
			lines[i] = tempLines.get(i);
		}
	}
	
	public String getText(){
		if (lines.length == 0){
			return "";
		}else if (lines.length == 1){
			return lines[0];
		}else{
			StringBuilder sb = new StringBuilder();
			for(int i=0; i<lines.length; i++){
				sb.append(lines[i]+" ");
			}
			return sb.toString();
		}
	}

	@Override
	public void draw(Canvas canvas) {
		Paint p = new Paint();
		
		if (drawBackground ){
			p.setARGB(192, 64, 64, 64);
			canvas.drawRect(getDimension(), p);
		}
		
		p.setARGB(255, 255, 255, 255);
		p.setTextSize(fontSize);
		for(int i=0; i<lines.length; i++){
			canvas.drawText(lines[i], getX()+1, getY()+(fontSize*lineHeight*(i+1)), p);
		}
	}

	/**
	 * {@link #fontSize}
	 */
	public void setTextSize(int fontSize) {
		this.fontSize = fontSize;
		calcLines(getText());
	}

}
